package peer.SearchManager;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import common.*;

public class SearchManager
{
	private static SearchManager Singleton;
	
	private ArrayList<InetSocketAddress> peers = new ArrayList<InetSocketAddress>();
	
	
	//old
	
	private int _searchID;
	
	private Map<Integer, Search> _Searches;
	
	private SearchManager()
	{
		_searchID = 0;
		_Searches = Collections.synchronizedMap(new HashMap<Integer, Search>());
	}
	
	public static SearchManager instance()
	{
		if(Singleton == null)
			Singleton = new SearchManager();
		
		return Singleton;
	}
	
	public synchronized int nextSearchID()
	{
		return ++_searchID;
	}
	
	public synchronized Set<Integer> getActiveSearchIDs()
	{
		return _Searches.keySet();
	}
	
	public synchronized boolean addNewSearch(String searchString)
	{
		Iterator<Integer> keys = _Searches.keySet().iterator();
		
		while(keys.hasNext())
		{
			Search s = _Searches.get(keys.next());
			
			if(searchString.equals(s.getSearchString()))
				return false;
		}
		
		Search newSearch = new Search(searchString);
		
		_Searches.put(Integer.valueOf(newSearch.getSearchID()), newSearch);
		return true;
	}

	public Search getSearch(Integer id)
	{
		return _Searches.get(id);
	}
	
	public void getPacket(Packet p, InetSocketAddress fromAddress)
	{
		switch(p.getType())
		{
		case 0x14://0001 0100 - found
			peers.add(fromAddress);
			break;
		case 0x1A://0001 1010 - request_file_response
			
			break;
		case 0x1E://0001 1110 - status_response
			
			break;
		default:
			break;
		}
	}
	
	public int getPeerCount()
	{
		return peers.size();
	}

	public InetSocketAddress getPeer(int i)
	{
		return peers.get(i);
	}
}
